package com.fubowen.reader.extension

import android.app.Activity
import android.content.Context
import android.content.Intent
import android.net.Uri
import androidx.activity.result.contract.ActivityResultContracts
import androidx.fragment.app.Fragment
import kotlin.math.roundToInt

fun Fragment.showFilePicker(type: String = "text/plain", callback: (Uri) -> Unit) {
    val launcher = registerForActivityResult(ActivityResultContracts.StartActivityForResult()) { result ->
        if (result.resultCode == Activity.RESULT_OK) {
            val data = result.data
            data?.data?.let { callback(it) }
        }
    }
    val intent = Intent(Intent.ACTION_OPEN_DOCUMENT)
    intent.addCategory(Intent.CATEGORY_OPENABLE)
    intent.type = type
    launcher.launch(intent)
}
fun Fragment.dpToPx(dp: Int) = (dp * this.resources.displayMetrics.density).roundToInt()